using System;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.CSharp.Stages;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using Sapphire.RSharp.Common;

namespace Sapphire.RSharp
{
  //http://codevanced.net/post/How-to-write-a-ReSharper-plugin.aspx

  public class SapphireStageProcess : CSharpDaemonStageProcessBase
  {
    private readonly ITroubleAnalyzer _troubleAnalyzer;

    public SapphireStageProcess(IDaemonProcess process)
      : base(process)
    {
      _troubleAnalyzer = new TroubleAnalyzer(process.GetCollectUsagesStageProcess());
    }

    public override void Execute(Action<DaemonStageResult> commiter)
    {
      HighlightInFile((file, consumer) =>
                        {
                          file.ProcessDescendants(_troubleAnalyzer.Finder);
                          file.ProcessDescendants(_troubleAnalyzer.Resolver);
                          file.ProcessDescendants(this, consumer);
                        },
                        commiter);
    }

    public override void ProcessBeforeInterior(IElement element, IHighlightingConsumer consumer)
    {

    }

    public override void ProcessAfterInterior(IElement element, IHighlightingConsumer consumer)
    {
      if (_troubleAnalyzer.Watched.Contains(element))
      {
        consumer.ConsumeHighlighting(element.GetDetectedDocumentRange(),
          _troubleAnalyzer.Highlighting);
      }

      base.ProcessAfterInterior(element, consumer);
    }
  }
}